#coding:utf-8
import json
from django.contrib import auth
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django_user_agents.utils import get_user_agent
from django.contrib.auth import authenticate, login, logout, get_backends
import re
from lovewith.views import site_info
from lovewith.api.qq_tools import QQ
from lovewith.api.weibo_tools import Weibo
from lovewith.account.views.modules.userapi import UserApi


#找回密码
def get_password(request):
    key = request.GET.get('k', None)
    confirm_data = None

    if request.user.is_authenticated():
        return HttpResponseRedirect('/u/%s/' % request.user.id)

    if key:
        confirm_data = UserApi.validate_getpwd_key(key)

    return render_to_response('user/get-password.jinja', {
        'confirm_data': confirm_data
    }, context_instance=RequestContext(request, processors=[site_info]))


#通过邮箱登录
def sign_with_email(request, email, pwd):
    user_data = UserApi.check_user(email=email)
    if user_data:
        username = user_data.username
        user_info = authenticate(username=username, password=pwd)
        if user_info is not None:
            if user_info.is_active:
                login(request, user_info)

                return True

    return False


#第三方登录
def sign(request, user_data, is_mobile=False):
    if user_data:
        for backend in get_backends():
            user_data.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)

        auth.login(request, user_data)

        next_page = request.GET.get('state')
        if next_page and next_page.find('lovewith.me') > 0:
            return HttpResponseRedirect(next_page)

        if is_mobile:
            return HttpResponseRedirect('/')
        else:
            return render_to_response('user/auth.jinja', {
                'isLogin': True,
            }, context_instance=RequestContext(request, processors=[site_info]))


#授权登录
def auth_sign(request):
    #判断UA
    user_agent = get_user_agent(request)
    next_page = request.GET.get('next') or None

    if request.user.is_authenticated():
        if next_page and not re.match(r'^http\:\/\/.*', next_page):
            return HttpResponseRedirect(next_page)

        if user_agent.is_mobile:
            return HttpResponseRedirect('/')
        else:
            return HttpResponseRedirect('/u/subscribe/all/')
    else:
        if user_agent.is_mobile:
            return render_to_response('mobile/sign.jinja', {
                'next_page': next_page,
            }, context_instance=RequestContext(request, processors=[site_info]))
        else:
            mt_home = request.GET.get('mt_home') or ''
            return render_to_response('user/sign.jinja', {
                'mt_home': mt_home,
                'action': 'sign'
            }, context_instance=RequestContext(request, processors=[site_info]))


#授权注册
def auth_join(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/u/subscribe/all/')

    return render_to_response('user/sign.jinja', {
        'action': 'join'
    }, context_instance=RequestContext(request, processors=[site_info]))


#微博授权(登录或注册)
def auth_by_weibo(request):
    #授权类型(注册登录: signinout || 同步数据: sync)
    auth_type = request.GET.get('auth_type') or 'signinout'

    #已登录并且不是在设置同步时直接跳转到首页
    if request.user.is_authenticated() and not auth_type == 'sync':
        return HttpResponseRedirect('/')

    code = 'code' in request.GET and request.GET.get('code') or None
    if not code:
        #授权失败
        return render_to_response('user/auth-fails.jinja', {
        }, context_instance=RequestContext(request, processors=[site_info]))

    weibo = Weibo()
    re = weibo.get_token(code)
    token = re.get('access_token')
    expires = re.get('expires_in')
    #保存token
    weibo.save_token(token, expires)
    #判断UA
    is_mobile = get_user_agent(request).is_mobile

    #获取授权用户Id
    account_id = weibo.get_token_uid()
    #获取详细的用户信息
    weibo_user_info = weibo.get_user_unfo(uid=account_id)
    #获取用户邮箱
    user_email = weibo.get_user_email() or ''

    user_data = UserApi.check_data(app_uid=account_id, account_type=1)

    #用户存在且未登录时直接登录
    if user_data and not request.user.is_authenticated():
        if not user_data.email and user_email:
            user_data.email = user_email
            user_data.save()

        #更新授权信息
        UserApi.update_auth(user_data, 1, weibo_user_info.get('name'), token, expires)

        #存在当前类型的帐号时候直接登录
        return sign(request, user_data, is_mobile=is_mobile)
    else:
        return render_to_response('user/auth.jinja', {
            'account_type': 'sina',
            'isLogin': False,
            'token': token,
            'expires': expires,
            'user_data': weibo_user_info,
            'user_email': user_email,
            'is_mobile': is_mobile,
        }, context_instance=RequestContext(request, processors=[site_info]))


#QQ授权(登录或注册)
def auth_by_qq(request):
    #授权类型(注册登录: signinout || 同步数据: sync)
    auth_type = request.GET.get('auth_type') or 'signinout'

    #已登录并且不是在设置同步时直接跳转到首页
    if request.user.is_authenticated() and not auth_type == 'sync':
        return HttpResponseRedirect('/')

    code = 'code' in request.GET and request.GET.get('code') or None
    if not code:
        #授权失败(用户取消了授权)
        return render_to_response('user/auth-fails.jinja', {
        }, context_instance=RequestContext(request, processors=[site_info]))

    qq = QQ()
    re = qq.get_token(code)
    if not 'expires_in' in re or not 'access_token' in re:
        #授权失败(刷新页面导致code过期)
        return render_to_response('user/auth-fails.jinja', {
        }, context_instance=RequestContext(request, processors=[site_info]))

    token = re.get('access_token')
    expires = re.get('expires_in')
    qq.save_token(token, expires)
    qq_openid = qq.get_open_id()
    is_mobile = False

    if request.GET.get('site') == 'mobile':
        is_mobile = True

    #qq空间用户数据
    qzone_user_data = qq.get_qzone_info()

    #ret不为0时认证接口报错，显示授权失败的提示
    if not qzone_user_data.get('ret') == 0:
        return render_to_response('user/auth-fails.jinja', {
        }, context_instance=RequestContext(request, processors=[site_info]))

    qzone_user_data.update({'app_uid': qq_openid})

    #腾讯微博用户数据(微博数据不一定存在，但QQ空间用户数据一定存在[即使没有开通QQ空间])
    qq_wb_user_data = qq.get_tencent_wb_user_info()
    #用微博name搜索到的本站用户数据
    wb_user_data = None
    #用qq_openid搜索到的本站用户数据
    qq_user_data = UserApi.check_data(app_uid=qq_openid, account_type=2)

    #用微博name搜索用户
    if qq_wb_user_data and qq_wb_user_data.get('ret') == 0:
        #以微博name作为openid尝试登录
        wb_user_data = UserApi.check_data(app_uid=qq_wb_user_data.get('data').get('name'), account_type=2)

    if not request.user.is_authenticated():
        if wb_user_data:
            '''
            如果腾讯微博帐号存在，更新user表中的app_uid为腾讯微博帐号，并更新授权信息
            '''
            wb_open_id = qq_wb_user_data.get('data').get('name')
            #以官方提供的openid作为user表的uid数据
            wb_user_data.app_uid = qq_openid
            wb_user_data.save()

            #更新授权信息
            UserApi.update_auth(wb_user_data, 2, wb_open_id, token, expires)

            return sign(request, wb_user_data, is_mobile=is_mobile)
        else:
            #qq空间帐号存在
            if qq_user_data:
                #以官方提供的openid作为user表的uid数据
                qq_user_data.app_uid = qq_openid
                qq_user_data.save()

                return sign(request, qq_user_data, is_mobile=is_mobile)

    return render_to_response('user/auth.jinja', {
        'account_type': 'qq',
        'isLogin': False,
        'token': token,
        'expires': expires,
        'user_data': qzone_user_data,
        'qzone_user_data': qzone_user_data,
        'user_email': '',
        'is_mobile': is_mobile,
    }, context_instance=RequestContext(request, processors=[site_info]))


#登出
def sign_out(request):
    next_url = request.GET.get('next') or '/'
    response = HttpResponseRedirect(next_url)
    #删除cookie
    response.delete_cookie('uinfo')

    logout(request)

    return response


#SSO登录
def auth_sso(request):
    result = {}

    if request.user.is_authenticated():
        result = {
            'id': request.user.id,
            'username': request.user.username,
            'email': request.user.email,
            'level': request.user.is_admin,
            'avatar': request.user.avatar
        }

    return HttpResponse(json.dumps(result))